package com.book.controller;

import com.book.entity.Admin;
import com.book.entity.User;
import com.book.repository.AdminRepository;
import com.book.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

/**
 * @author BeijiRonin
 * @date 2020/11/12
 */
@RestController
@RequestMapping("/book")
public class BookHandleer {
    @Autowired
    private BookRepository bookRepository;
    @Autowired
    private AdminRepository adminRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<User> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageRequest request = PageRequest.of(page,size);

        return bookRepository.findAll(request);
    }

    @GetMapping("/adminfindAll/{page}/{size}")
    public Page<Admin> adminfindAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageRequest request = PageRequest.of(page,size);

        return adminRepository.findAll(request);
    }

    @PostMapping("/save")
    public String save(@RequestBody User book){
        User result = bookRepository.save(book);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public User findById(@PathVariable("id") Integer id){
        return bookRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody User user){
        User result = bookRepository.save(user);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @PostMapping("/adminsave")
    public String adminsave(@RequestBody Admin admin){
        Admin result = adminRepository.save(admin);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        bookRepository.deleteById(id);
    }

}
